import {
  getGoodsDetail
} from "../../../../api/goods"

import {
  getCartList
} from "@/api/cart"
import storeBindingsBehavior from "@/behaviors/userBehaviors"
import {
  addToCart
} from "@/api/cart"
Page({
  behaviors: [storeBindingsBehavior],
  async GoodsDetailData(goodId) {
    const {
      code,
      data
    } = await getGoodsDetail(goodId)
    if (code === 200) {
      this.setData({
        ...data
      })
    } else {
      wx.showToast({
        title: '获取商品详情失败',
        icon: "error"
      })
    }
  },
  onLoad(option) {
    this.setData({
      goodsId: option.goodsId
    });
    this.GoodsDetailData(this.data.goodsId);
    this.storeBindings.updateStoreBindings()
    this.getCartCount()
  },
  async getCartCount() {
  
    if (!this.data.token) {
      return
    }
    console.log(!this.data.token);
    const {
      code,
      data
    } = await getCartList()
    if (code === 200 && data.length !== 0) {
      let allcount = 0
      data.forEach(item => {
        allcount += item.count
      });
      this.setData({
        allCount: (allcount >= 99 ? '99+' : allcount) + ''
      })
    }
  
  },
  data: {
    show: false, // 加入购物车和立即购买时显示的弹框
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    allCount: '1', // 展示购物车商品的数量
    goodDetail: {},
    buyNow: 0, // 控制是加入还是立即购买 0 加入
  },
  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })

  },
  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyNow: 1,
      count: 1
    })
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({
      show: false
    })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    this.setData({
      count: Number(event.detail)
    })
  },

  // 弹框的确定按钮
  async handleSubmit() {
    // 获取相关数据
    const {
      goodsId,
      token,
      count,
      blessing,
      buyNow
    } = this.data

    // 判断用户是否继续了登录
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }
    // 说明加入购物车
    if (buyNow === 0) {
      console.log(blessing);
      const res = await addToCart({
        goodsId,
        count,
        blessing
      })
      if (res.code === 200) {
        wx.showToast({
          title: '已加入购物车',
        })
        this.getCartCount()
      }
      // 立即购买
    } else {
      wx.navigateTo({
        url: `/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`,
      })
    }
    // 关闭弹框
    this.setData({
      show: false
    })
  },

})